<?php
namespace app\organize\model;

use think\Model;
use think\DB;

class department extends Model
{
	/**
     * 获取所有部门
     * @return mixed
     */
    public static function getDepartmentList( $map = array() )
    {
        $result = cache('department_list');
        if (!$result) {
        	$result = self::find(1)->toArray();
        	$result['spread'] = true;
        	$map['parent_id'] = 1;
			$children= self::where($map)->column('id,name,parent_id');
            foreach ($children as $key => $value) {
                $children[$key]['text'] = $value['name'];
                $children[$key]['value'] = $value['id'];
            }
			$result['children'] = array_values($children);
            if (!$result) {
            	cache('department_list', $result);
            }
        }
        return $result;
    }

    /**
     * 添加或更新部门
     * @return mixed
     */
    public function setDepartment($data = array() , $id = 0)
    {
    	if($id)
    	{
    		$ret = self::where('id',$id)->update($data);
    	}
    	else{
    		$ret = self::insert($data);
    	}
    	return $ret;
    }

    /**
     * 删除部门
     * @return mixed
     */
    public function delDepartment($id)
    {
    	$ret = self::delete($id);
    	return $ret;
    }

    /**
     * 获取部门所有成员
     * @return mixed
     */
    public static function getUserByDepartId( $id, $keywords, $page, $pageSize, $iterate = false )
    {	
        $result = cache('department_user_'.$id);
        if( $id != 1 ) //是否查询子部门
        {
        	$map = ['ud.department_id'=>$id];
        }
        else{
        	$map = ['d.parent_id'=>1];
        }
        if(!empty($keywords)){
            $map['u.username|u.position'] = ['like','%'.$keywords.'%'];
        }
        if (!$result) 
        {
        	$limit = ($page-1)*$pageSize.','.$pageSize;
        	$count = Db::name('user_department')
				->alias('ud')
				->join('department d','d.id = ud.department_id')
				->join('user u','u.id = ud.user_id')
				->where($map)
				->group('u.id')
				->count();
        	$result = Db::name('user_department')
				->alias('ud')
				->join('user u','u.id = ud.user_id')
				->join('department d','d.id = ud.department_id')
				->where($map)
				->field('u.id,u.username,u.mobile,u.gender,u.position')
				->group('u.id')
				->limit($limit)
				->select();
				// echo Db::name('user_department')->getLastSql();
            if (!$result) {
            	cache('department_list'.$id, $result);
            }
        }
        return ['count'=>$count,'data'=>$result];
    }

}